package com.example.Schedule;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.HttpClientUtils;
import com.example.common.MyStringUtil;
import com.example.dao.BaseInfo;
import com.example.dao.HnyySscPickingCartonDetailsDTO;
import com.example.entity.HnyySscPickingCartonDetail;
import com.example.service.HnyySscPickingCartonDetailService;
import com.example.service.HnyyZsmCodeInfoService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;

@Component

public class SimpleScheduleTask {

    public static Map<String,Map<String,String>> tyxydm = new HashMap<>();

    private static Logger logger = LoggerFactory.getLogger(SimpleScheduleTask.class);

    public static SimpleDateFormat sdfS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static SimpleDateFormat sdfD = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private HnyySscPickingCartonDetailService hnyySscPickingCartonDetailService;
    @Autowired
    private HnyyZsmCodeInfoService hnyyZsmCodeInfoService;

    public String queryDxm(String name,String code,String inv,String opter,String opterName,String ak,String sk,String fromBillSc){
        Map map = new HashMap();
        map.put("name",name);
        map.put("code",code);
        map.put("opter",opter);
        System.out.println("2==========>"+JSONObject.toJSONString(map));
        tyxydm.put(inv,map);
        System.out.println("tyxydm===>"+JSONObject.toJSONString(tyxydm));
        System.out.println("inv"+inv+fromBillSc);
        List<HnyySscPickingCartonDetail> hnyySscPickingCartonDetails = hnyySscPickingCartonDetailService.queryNew(inv,fromBillSc);
        System.out.println("222222=====>"+JSONObject.toJSONString(hnyySscPickingCartonDetails));
        for(HnyySscPickingCartonDetail hnyySscPickingCartonDetail : hnyySscPickingCartonDetails){
            System.out.println("hnyySscPickingCartonDetails====>"+JSONObject.toJSONString(hnyySscPickingCartonDetail));
            BaseInfo baseInfo = new BaseInfo();
            baseInfo.setInfno("3561");
            baseInfo.setMsgid(hnyySscPickingCartonDetail.getSscPickingCartonDetailId().toString());
            baseInfo.setInsuplc_admdvs("null");
            baseInfo.setMdtrtarea_admvs("430000");
            baseInfo.setRecer_sys_code(hnyySscPickingCartonDetail.getClientId().toString());
            baseInfo.setSigntype("SM3");
            baseInfo.setInfver("1.0.0");
            baseInfo.setOpter_type("1");
            baseInfo.setOpter(opter);
            baseInfo.setOpter_name(opterName);
            baseInfo.setInf_time(sdfS.format(new Date()));
            baseInfo.setFixmedins_code(hnyySscPickingCartonDetail.getFixmedinsHilistId());
            baseInfo.setFixmedins_name(hnyySscPickingCartonDetail.getFixmedinsHilistName());

            baseInfo.setDev_safe_info("null");
            baseInfo.setCainfo("null");
            baseInfo.setSign_no("null");
            Map data = new HashMap();
            HnyySscPickingCartonDetailsDTO hnyySscPickingCartonDetailsDTO = HnyySscPickingCartonDetailsDTO.getHnyySscPickingCartonDetailsDTO(hnyySscPickingCartonDetail, hnyySscPickingCartonDetailService, hnyyZsmCodeInfoService,inv);
            System.out.println("hnyySscPickingCartonDetailsDTO=========>"+JSONObject.toJSONString(hnyySscPickingCartonDetailsDTO));

            data.put("data",hnyySscPickingCartonDetailsDTO);
            baseInfo.setInput(data);
            System.out.println("baseInfo======>"+JSONObject.toJSONString(baseInfo));
            Map result = pushDxm(baseInfo,ak,sk);
            System.out.println("result===>"+result);
            String msg = (String) result.get("warn_msg");
            String errMsg = (String) result.get("err_msg");
            HnyySscPickingCartonDetail hnyySscPickingCartonDetailUpdate = new HnyySscPickingCartonDetail();
            hnyySscPickingCartonDetailUpdate.setSscPickingCartonDetailId(hnyySscPickingCartonDetail.getSscPickingCartonDetailId());
            if("成功".equals(msg)){
                hnyySscPickingCartonDetailUpdate.setExecFlag("FINISH");
            }else {
                // 再发一次请求
                String newProp = MyStringUtil.calculateProp(hnyySscPickingCartonDetailsDTO);
                hnyySscPickingCartonDetailsDTO.setProp(newProp);
                Map retryData = new HashMap();
                retryData.put("data", hnyySscPickingCartonDetailsDTO);
                baseInfo.setInput(retryData);

                Map retryResult = pushDxm(baseInfo, ak, sk);
                System.out.println("retryResult===>" + retryResult);
                String retryMsg = (String) retryResult.get("warn_msg");
                String retryErrMsg = (String) retryResult.get("err_msg");

                if ("成功".equals(retryMsg)) {
                    hnyySscPickingCartonDetailUpdate.setExecFlag("FINISH");
                } else {
                    // 失败
                    hnyySscPickingCartonDetailUpdate.setExecFlag("NEWRESEND");
                    hnyySscPickingCartonDetailUpdate.setExecMsg(retryErrMsg);
                    hnyySscPickingCartonDetailService.update(hnyySscPickingCartonDetailUpdate);
                    return "失败";
                }

            }
            System.out.println("12121"+JSONObject.toJSONString(hnyySscPickingCartonDetailUpdate));
            hnyySscPickingCartonDetailService.update(hnyySscPickingCartonDetailUpdate);
        }
        return "成功";
    }

    public Map pushDxm(BaseInfo baseInfo,String ak,String sk) {
        //=========================获取连接=========================
        try {
            //创建客户端:用来创建web客户端的
            CloseableHttpClient client = HttpClientUtils.createIgnoreCertClient();
//        CloseableHttpClient client = HttpClientBuilder.create().build();
            //获取连接请求:用来设置接口的
            HttpPost httpPost = new HttpPost("https://dms.hun.hsip.gov.cn/isp-api/powercsb/3561");
            //设置响应模型:用来发送请求的
            CloseableHttpResponse response = null;
            //设置响应参数模型：专门获取响应参数
            HttpEntity entity = null;

//        Map<String,Object> data  = new HashMap<>();

            //设置请求头
            //原代码hhttpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("_api_name", "3561");
            httpPost.setHeader("_api_version", "1.0.0");
            long timestamp = Instant.now().toEpochMilli();
            httpPost.setHeader("_api_timestamp", String.valueOf(timestamp));
            httpPost.setHeader("_api_access_key", ak);
            String sign = signCalc("3561","1.0.0",ak,sk,String.valueOf(timestamp));
            httpPost.setHeader("_api_signature", sign);
            httpPost.setHeader("Accept-Charset", "UTF-8");


            String dataJson = JSONObject.toJSONString(baseInfo);

            logger.info(dataJson);
            logger.info("----------开始发送----------");

            //=========================连接=========================

            //获取响应模型
            httpPost.setEntity(new StringEntity(dataJson, "UTF-8"));
            response = client.execute(httpPost);
            entity = response.getEntity();
            String entityStr = EntityUtils.toString(entity, "UTF-8");
            logger.info("响应状态为:{}", response.getStatusLine().getStatusCode());
            logger.info("响应内容:{}", entityStr);
            Map map = JSON.parseObject(entityStr);
            return map;
        } catch (Exception e) {
            logger.info("获取追溯码上传列表失败!");
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        //=========================获取请求参数=========================

        //获取响应参数
        return null;
    }

    public String signCalc(String apiName,String apiVersion,String apiAccessKey,String apiEcreKey,String apiTimestamp) {
        String param = "_api_access_key="+ apiAccessKey +"&"+ "_api_name="+ apiName +"&"+"_api_timestamp="+ apiTimestamp +"&"+"_api_version=" +apiVersion;
        String sign = null;
        try {
            sign = hmacSha1Base64(apiEcreKey,param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }

    /**
     * 使用 HmacSHA1 加密字符串，并返回 Base64 编码结果
     * @param secret  密钥
     * @param message 待加密的字符串
     * @return Base64 编码的签名
     */
    public static String hmacSha1Base64(String secret, String message) throws Exception {
        // 1. 获取 HmacSHA1 算法的 Mac 实例
        Mac mac = Mac.getInstance("HmacSHA1");

        // 2. 将密钥转换为字节数组（UTF-8 编码）
        byte[] keyBytes = secret.getBytes("UTF-8");
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // 3. 初始化 Mac 实例
        mac.init(signingKey);

        // 4. 加密消息（UTF-8 编码）
        byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));

        // 5. 将字节数组转换为 Base64 字符串
        return Base64.getEncoder().encodeToString(rawHmac);
    }
}
